/*
 * Copyright (C), 2020, 安徽艾伦家居饰品有限公司
 * FileName: UserDetailsServiceImpl
 * Author:   Allen
 * Date:     2020/8/15
 * Description: UserDetailsService的实现
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.haoyu.auth.core.service.impl;

import com.haoyu.auth.client.constant.AuthServiceConstant;
import com.haoyu.auth.client.dto.UserInfoDTO;
import com.haoyu.auth.client.rest.UserDetailsResource;
import com.haoyu.auth.core.entity.UserDO;
import com.haoyu.auth.client.constant.AuthEnumConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;

/**
 * UserDetailsService的实现
 *
 * @author Allen
 * @date 2020-07-10
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    /**
     * 获取用户信息接口
     */
    @Autowired
    private Map<String, UserDetailsResource> userDetailsResources;

    /**
     * 加载userService
     */
    @Autowired
    private UserServiceImpl userService;
    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 用户不存在异常信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取client_id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String clientId;
        // 当授权模式为authorization_code,authentication为null,这时给设置一个默认的clientId用于对应一个获取用户信息服务
        if (authentication != null) {
            clientId = ((User) authentication.getPrincipal()).getUsername();
        } else {
            UserDO userDO = userService.getByUsername(username);
            if (userDO != null) {
                log.debug("使用Auth授权服务器自己认证用户登录，当前用户为--> {}，登陆账号为--> {}", userDO.getUserName(),
                        userDO.getLoginName());
                return new UserInfoDTO(userDO.getLoginName(), userDO.getLoginPassword(), true, new ArrayList());
            }
            clientId = AuthServiceConstant.DEFAULT_CLIENT_ID;
        }
        // 获取用户
        UserDetailsResource resource = userDetailsResources.get(clientId);
        UserInfoDTO userInfo;
        try {
            userInfo = resource.loadUserByUsername(username);
            // 获取用户权限
            // List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            // if (StringUtils.isNoneEmpty(user.getAuthorities())) {
            // Stream.of(user.getAuthorities().split(","))
            // .forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
            // }
        } catch (Exception exception) {
            log.error("Not found any user for username：{}", username);
            throw new UsernameNotFoundException(String.format(AuthEnumConstant.USER_BAN.message(), username));
        }
        return userInfo;
    }

}
